from flask import Blueprint, request, send_file
from entity.Response import success,error
from entity.Drug import Drug
from db import db
import pandas as pd
from io import BytesIO

drugController = Blueprint('drugController',__name__)

"""
添加一条药品信息
input
drug form
output
none
"""
@drugController.route('/addDrugInfo',methods=['POST'])
def addDrugInfo():
    name = request.get_json().get('name')
    approvalNumber = request.get_json().get('approvalNumber')
    producer = request.get_json().get('producer')
    ingredient = request.get_json().get('ingredient')
    character = request.get_json().get('character')
    guidance = request.get_json().get('guidance')
    sideEffects = request.get_json().get('sideEffects')
    introduction = request.get_json().get('introduction')
    cover = request.get_json().get('cover')

    drug = Drug.query.filter_by(name=name).first()
    if drug != None:
        return error(message='药品名称已存在')
    
    drug = Drug(name,cover,approvalNumber,producer,ingredient,character,guidance,sideEffects,introduction)
    db.session.add(drug)
    db.session.commit()
    return success(message='药品添加成功')

"""
获取全部药品信息
input:
none
output:
drug list
"""
@drugController.route('/getAllDrugInfo',methods=['GET'])
def getAllDrugInfo():
    drugList = Drug.query.all()
    dataList = []
    for drug in drugList:
        dataList.append(drug.to_dict())

    return success(message='获取药品列表成功',data=dataList)

"""
删除指定药品
input:
id
output:
none
"""
@drugController.route('/deleteDrug',methods=['DELETE'])
def deleteDrug():
    drugId = request.args.get('drugId')
    drug = Drug.query.filter_by(id=drugId).first()
    print(drugId)
    if drug == None:
        return error(message='药品信息不存在')
    
    db.session.delete(drug)
    db.session.commit()

    return success(message='删除成功')

"""
导出全部药品为CSV并返回给前端
input:
none:
output:
csv file
"""
@drugController.route('/exportDrug',methods=['GET'])
def exportDrug():
    drugList = Drug.query.all()
    drugData = []
    for drug in drugList:
        drugData.append(drug.to_dict())
    df = pd.DataFrame(drugData)
    
    csv_buffer = BytesIO()
    df.to_csv(csv_buffer, index=False, encoding='utf-8-sig')
    csv_buffer.seek(0)
    
    return send_file(
        csv_buffer,
        mimetype='text/csv',
        as_attachment=True,
        download_name='drugs.csv'
    )

"""
更新药品信息
input:
drug form
output:
none
"""
@drugController.route('/updateDrugInfo',methods=['PUT'])
def updateDrugInfo():
    id = request.get_json().get('id')
    name = request.get_json().get('name')
    approvalNumber = request.get_json().get('approvalNumber')
    producer = request.get_json().get('producer')
    ingredient = request.get_json().get('ingredient')
    character = request.get_json().get('character')
    guidance = request.get_json().get('guidance')
    sideEffects = request.get_json().get('sideEffects')
    introduction = request.get_json().get('introduction')
    cover = request.get_json().get('cover')

    drug = Drug.query.filter_by(id=id).first()
    if drug == None:
        return error(message='药品信息不存在')
    
    Drug.query.filter_by(id=id).update({'name': name,'approval_number': approvalNumber, 'producer': producer, 'ingredient': ingredient, 'character': character, 'guidance': guidance, 'side_effects': sideEffects, 'introduction': introduction,'cover': cover})
    db.session.commit()
    return success(message='药品信息更新成功')